package com.lxl.zookeeper;

import org.apache.zookeeper.*;

import java.io.IOException;

/**
 * @Author lixilin
 * @Date 2022/1/16 9:47
 * @Description 模拟服务端节点想zookeeper注册服务
 */
public class DistributeServer {
    public static void main(String[] args) throws Exception{
        DistributeServer server = new DistributeServer();
        // 创建连接
        server.getConnect();
        // 注册服务
        server.register(args[0]);
        // 业务逻辑
        server.business();
    }

    private void business() throws InterruptedException {
        Thread.sleep(Long.MAX_VALUE);
    }

    private void register(String hostname) throws KeeperException, InterruptedException {
        /*
         String path 节点路径
         byte[] data  往节点保存的数据,这里保存主机名称
         List<ACL> acl 权限控制
         CreateMode createMode 节点类型
         */
        String path = zkClient.create("/servers/server", hostname.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        System.out.println(hostname + "is online");
    }
    // zk集群主机名称及端口
    private String connectString ="node101:2181,node102:2181,node103:2181";
    // 会话超时时间
    private int sessionTimeout=2000;
    private ZooKeeper zkClient;
    private void getConnect() throws IOException {
        zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                // 监听器处理逻辑

            }
        });
    }
}
